<template>
  <div class="app-container">
    <!-- 时间范围选择 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据概览 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-header">
            <span>总交易额</span>
            <el-tooltip content="平台所有订单交易金额总和" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="data-body">
            <div class="data-value">¥{{ formatNumber(platformStats.totalAmount) }}</div>
            <div class="data-trend" :class="{ up: platformStats.amountGrowth > 0 }">
              {{ platformStats.amountGrowth > 0 ? '↑' : '↓' }} {{ Math.abs(platformStats.amountGrowth) }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-header">
            <span>订单总数</span>
            <el-tooltip content="平台所有订单数量" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="data-body">
            <div class="data-value">{{ formatNumber(platformStats.totalOrders) }}</div>
            <div class="data-trend" :class="{ up: platformStats.orderGrowth > 0 }">
              {{ platformStats.orderGrowth > 0 ? '↑' : '↓' }} {{ Math.abs(platformStats.orderGrowth) }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-header">
            <span>活跃商家数</span>
            <el-tooltip content="当前有交易的商家数量" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="data-body">
            <div class="data-value">{{ formatNumber(platformStats.activeMerchants) }}</div>
            <div class="data-trend" :class="{ up: platformStats.merchantGrowth > 0 }">
              {{ platformStats.merchantGrowth > 0 ? '↑' : '↓' }} {{ Math.abs(platformStats.merchantGrowth) }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-header">
            <span>平均客单价</span>
            <el-tooltip content="平均每笔订单金额" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="data-body">
            <div class="data-value">¥{{ formatNumber(platformStats.averageOrderAmount) }}</div>
            <div class="data-trend" :class="{ up: platformStats.averageGrowth > 0 }">
              {{ platformStats.averageGrowth > 0 ? '↑' : '↓' }} {{ Math.abs(platformStats.averageGrowth) }}%
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>交易趋势</span>
              <el-radio-group v-model="trendType" size="small" @change="handleTrendTypeChange">
                <el-radio-button label="amount">交易金额</el-radio-button>
                <el-radio-button label="count">订单数量</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" class="chart"></div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div ref="pieChartRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>数据明细</span>
          <el-button type="primary" @click="handleExport">导出数据</el-button>
        </div>
      </template>
      <el-table :data="detailData" v-loading="loading">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="orderCount" label="订单数" />
        <el-table-column prop="amount" label="交易金额">
          <template #default="{ row }">
            ¥{{ formatNumber(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="merchantCount" label="活跃商家" />
        <el-table-column prop="averageAmount" label="平均客单价">
          <template #default="{ row }">
            ¥{{ formatNumber(row.averageAmount) }}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getPlatformStats, getPlatformTrend } from '@/api/data'

// 查询参数
const queryParams = reactive({
  dateRange: [],
  pageNum: 1,
  pageSize: 10
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 数据统计
const loading = ref(false)
const platformStats = ref({
  totalAmount: 0,
  amountGrowth: 0,
  totalOrders: 0,
  orderGrowth: 0,
  activeMerchants: 0,
  merchantGrowth: 0,
  averageOrderAmount: 0,
  averageGrowth: 0
})

// 图表相关
const trendType = ref('amount')
const trendChartRef = ref(null)
const pieChartRef = ref(null)
let trendChart = null
let pieChart = null

// 明细数据
const detailData = ref([])
const total = ref(0)

// 获取平台统计数据
const getStats = async () => {
  try {
    const { data } = await getPlatformStats()
    platformStats.value = data
  } catch (error) {
    console.error('获取平台统计数据失败:', error)
  }
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  trendChart = echarts.init(trendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '交易金额',
        type: 'line',
        smooth: true,
        data: [],
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  }
  trendChart.setOption(option)
}

// 初始化饼图
const initPieChart = () => {
  if (!pieChartRef.value) return
  pieChart = echarts.init(pieChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  pieChart.setOption(option)
}

// 更新趋势图表数据
const updateTrendChart = async () => {
  try {
    const { data } = await getPlatformTrend({
      type: trendType.value,
      ...queryParams
    })
    const option = {
      xAxis: {
        data: data.dates
      },
      series: [
        {
          name: trendType.value === 'amount' ? '交易金额' : '订单数量',
          data: data.values
        }
      ]
    }
    trendChart?.setOption(option)
  } catch (error) {
    console.error('获取趋势数据失败:', error)
  }
}

// 更新饼图数据
const updatePieChart = () => {
  const option = {
    series: [
      {
        data: [
          { value: platformStats.value.pendingOrders, name: '待付款' },
          { value: platformStats.value.processingOrders, name: '处理中' },
          { value: platformStats.value.completedOrders, name: '已完成' },
          { value: platformStats.value.canceledOrders, name: '已取消' }
        ]
      }
    ]
  }
  pieChart?.setOption(option)
}

// 日期变化
const handleDateChange = () => {
  getStats()
  updateTrendChart()
}

// 趋势类型变化
const handleTrendTypeChange = () => {
  updateTrendChart()
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 分页相关
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getStats()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getStats()
}

// 格式化数字
const formatNumber = (num) => {
  return num?.toLocaleString()
}

// 监听窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  pieChart?.resize()
}

onMounted(() => {
  getStats()
  initTrendChart()
  initPieChart()
  updateTrendChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  pieChart?.dispose()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
}

.data-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  color: #606266;
}

.data-body {
  display: flex;
  align-items: baseline;
  gap: 12px;
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.data-trend {
  font-size: 14px;
  color: #f56c6c;
}

.data-trend.up {
  color: #67c23a;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 100%;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 